package pw.caffe;

import java.util.List;
import java.util.Map;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import pw.caffe.common.IAction;
import pw.caffe.common.net.NEXRequest;
import pw.caffe.common.net.NEXResponse;

public class ServerHandler extends IoHandlerAdapter {

	private Map<String, IAction> actionList;

	public void setActionList(Map<String, IAction> actionList) {
		this.actionList = actionList;
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		super.exceptionCaught(session, cause);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		// 解码后的请求
		System.out.println("echo hello world");
		NEXRequest request = (NEXRequest) message;

		IAction action = actionList.get(request.getCommand());
		action.setIoSession(session);
		List<NEXResponse> responseList = action.handleNEXRequest(request);
		for (int i = 0; i < responseList.size(); i++) {
			session.write(responseList.get(i));
		}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		super.messageSent(session, message);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		super.sessionClosed(session);
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		super.sessionCreated(session);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		super.sessionIdle(session, status);
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		super.sessionOpened(session);
	}
}
